<template>
  <div class="task-review-dialog-container">
    <el-dialog title="任务审核" v-model="state.isShowDialog" width="600px">
      <div v-if="state.task" class="task-info">
        <h3>{{ state.task.title }}</h3>
        <div class="task-meta">
          <div class="meta-item">
            <span class="label">提交时间：</span>
            <span>{{ formatDate(state.task.updated_at) }}</span>
          </div>
          <div class="meta-item">
            <span class="label">提交学生：</span>
            <span>{{ getUserName(state.task.assignee_id) }}</span>
          </div>
        </div>

        <div class="task-description">
          <div class="label">任务描述：</div>
          <div class="content">{{ state.task.description }}</div>
        </div>

        <div class="task-files">
          <div class="file-item" v-if="state.task.taskfile">
            <span class="label">任务文件：</span>
            <el-link type="primary" @click="downloadFile('task')">{{ getFileName(state.task.taskfile) }}</el-link>
          </div>
          <div class="file-item" v-if="state.task.resultfile">
            <span class="label">提交文件：</span>
            <el-link type="success" @click="downloadFile('result')">{{ getFileName(state.task.resultfile) }}</el-link>
          </div>
        </div>

        <el-divider content-position="center">审核意见</el-divider>

        <el-form ref="reviewFormRef" :model="state.reviewForm" :rules="rules" label-width="100px">
          <el-form-item label="审核结果" prop="status">
            <el-radio-group v-model="state.reviewForm.status">
              <el-radio :label="3">通过</el-radio>
              <el-radio :label="4">不通过</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核意见" prop="comment">
            <el-input
              v-model="state.reviewForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见">
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <div v-else class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" size="default">取 消</el-button>
          <el-button type="primary" @click="submitReview" size="default" :loading="state.loading">
            提交审核
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="taskReviewDialog">
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getTaskDetail, downloadTaskFile } from "/@/views/task/task";
import Axios from "/@/utils/Axios";

// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);
const reviewFormRef = ref();

// 表单验证规则
const rules = {
  status: [
    { required: true, message: "请选择审核结果", trigger: "change" }
  ],
  comment: [
    { required: true, message: "请输入审核意见", trigger: "blur" },
    { min: 2, max: 200, message: "审核意见长度在2到200个字符之间", trigger: "blur" }
  ]
};

// 定义变量内容
const state = reactive({
  isShowDialog: false,
  loading: false,
  users: [],
  task: null,
  reviewForm: {
    status: 3, // 默认通过
    comment: ""
  }
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取用户名
const getUserName = (userId) => {
  const user = state.users.find(u => u.user.id === userId);
  return user ? user.user.name : userId;
};

// 获取文件名
const getFileName = (filePath) => {
  if (!filePath) return "";
  return filePath.match(/[^/]+$/)[0];
};

// 下载文件
const downloadFile = (fileType) => {
  if (!state.task) return;

  const fileName = fileType === 'task' ? state.task.taskfile : state.task.resultfile;

  if (!fileName) {
    ElMessage.warning("文件不存在");
    return;
  }

  downloadTaskFile(state.task.id).then((response) => {
    // 提取文件名
    const filename = fileName.match(/[^/]+$/)[0];

    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }).catch(() => {
    ElMessage.error("下载文件失败");
  });
};

// 打开弹窗
const openDialog = (row) => {
  state.isShowDialog = true;
  state.task = row;
  state.reviewForm = {
    status: 3,
    comment: ""
  };

  // 获取所有用户
  Axios.get("/backapi/users").then((res) => {
    state.users = res.data.allUser;
  }).catch(() => {
    ElMessage.error("获取用户列表失败");
  });

  // 获取任务详情
  getTaskDetail(row.id).then(res => {
    state.task = res.task;
  }).catch(() => {
    ElMessage.error("获取任务详情失败");
    closeDialog();
  });
};

// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
  state.task = null;
};

// 提交审核
const submitReview = () => {
  reviewFormRef.value.validate((valid) => {
    if (!valid || !state.task) return;

    state.loading = true;

    // 调用审核接口
    Axios.post(`/backapi/tasks/${state.task.id}/review`, {
      status: state.reviewForm.status,
      comment: state.reviewForm.comment,
      operator_id: "admin" // 使用管理员身份
    }).then(res => {
      if (res.success === "1") {
        ElMessage.success("审核提交成功");
        closeDialog();
        emit("refresh");
      } else {
        ElMessage.error(res.message || "审核提交失败");
      }
      state.loading = false;
    }).catch(error => {
      ElMessage.error(error.message || "审核提交失败");
      state.loading = false;
    });
  });
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.task-review-dialog-container {
  .task-info {
    h3 {
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 18px;
    }

    .task-meta {
      display: flex;
      margin-bottom: 15px;

      .meta-item {
        margin-right: 20px;
        font-size: 14px;

        .label {
          color: #606266;
          margin-right: 5px;
        }
      }
    }

    .task-description {
      margin-bottom: 15px;

      .label {
        color: #606266;
        margin-bottom: 5px;
        font-weight: bold;
      }

      .content {
        background-color: #f5f7fa;
        padding: 10px;
        border-radius: 4px;
        white-space: pre-line;
      }
    }

    .task-files {
      margin-bottom: 15px;

      .file-item {
        margin-bottom: 8px;

        .label {
          color: #606266;
          margin-right: 10px;
        }
      }
    }
  }

  .loading-container {
    padding: 20px 0;
  }
}
</style>
